package com.pinyougou.cart.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.common.util.IdWorker;
import com.pinyougou.pojo.Order;
import com.pinyougou.service.OrderService;
import com.pinyougou.service.WeixinPayService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference(timeout = 10000)
    private OrderService orderService;
    @Reference(timeout = 10000)
    private WeixinPayService weixinPayService;

    @PostMapping("/save")
    public boolean save(@RequestBody Order order, HttpServletRequest request) {
        //获取登录用户名
        try {
            String userId = request.getRemoteUser();
            order.setUserId(userId);
            orderService.save(order);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @GetMapping("/genPayCode")
    public Map<String, String> genPayCode() {
        //创建分布式id生成器
        IdWorker idWorker = new IdWorker();
        /*调用生成微信支付二维码服务方法*/
        return weixinPayService.genPayCode(String.valueOf(idWorker.nextId()), "1");
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/queryPayStatus")
    public Map<String, Integer> queryPayStatus(String outTradeNo) {
        Map<String, Integer> data = new HashMap<>();
        data.put("status", 3);
        try {
            // 调用查询订单接口
            Map<String, String> resMap = weixinPayService.queryPayStatus(outTradeNo);
            if (resMap != null && resMap.size() > 0) {
                // 判断是否支付成功
                if ("SUCCESS".equals(resMap.get("trade_state"))) {
                    data.put("status", 1);
                }
                if ("NOTPAY".equals(resMap.get("trade_state"))) {
                    data.put("status", 2);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }
}











